package com.markyao.service;

import com.alibaba.fastjson.JSON;
import com.markyao.miaosha.GoodsKey;
import com.markyao.miaosha.KeyPrefix;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class RedisService {

    @Autowired
    RedisTemplate redisTemplate;
    public <T> boolean set(KeyPrefix prefix, String key, T value , int exTime) {
        //存入redis(秒杀路径path以及商品的库存量)
        //key的规则: prefix +key
        String valueStr = beanToString(value);
        if (valueStr==null||valueStr.length()==0){
            return false;
        }
        //生成key
        String realKey=prefix.getPrefix()+key;
        if (exTime==0){
            //要是时间过期则活动已经结束
            redisTemplate.opsForValue().set(realKey,valueStr);
        }else{
            //设置过期时间
            redisTemplate.opsForValue().set(realKey,valueStr,exTime, TimeUnit.SECONDS);
        }
        return true;
    }
    //将实体类转化为string用以存入redis
    public static <T> String beanToString(T value) {
        if(value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class) {
            return ""+value;
        }else if(clazz == String.class) {
            return (String)value;
        }else if(clazz == long.class || clazz == Long.class) {
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }

    //获取秒杀路径path
    public String getPath(KeyPrefix prefix, Integer uid, long goodsId) {
        String realKey=prefix.getPrefix()+uid+"-"+goodsId;
        ValueOperations<String,String> valueOperations = redisTemplate.opsForValue();
        String  realPath = valueOperations.get(realKey);
        return realPath;
    }

    //用以减少秒杀货品的库存
    public long decr(GoodsKey getSeckillGoodsStock, String s) {
        //key的规则: prefix +key
        String prefix = getSeckillGoodsStock.getPrefix();
        String key=prefix+s;
        //从redis减少库存
        Long decrement = redisTemplate.opsForValue().decrement(key);
        return decrement;
    }
}
